<template page>
    <div class="common-layout" style="margin: 0;">
        <el-container>
            <el-header>
                <el-button style="float: left;background-color: transparent;border: none;" size="large" type="" :icon="Back"
                           @click="back()" />
                <div style="margin-right: 40%;">
                    <span>加入拼车</span>
                </div>
            </el-header>
            <el-main>
                <el-card class="box-card" :data="vehicleTrip">
                    <div class="text item">{{ '行程路线: ' + vehicleTrip.adcRoutePrice.start_route + '→' +
                        vehicleTrip.adcRoutePrice.end_route }}</div>
                    <div class="text item">{{ '出发时间: ' + formattedDate +'&nbsp;&nbsp;&nbsp;&nbsp;'+ formattedTime}}</div>
                    <div class="text item">{{ '已拼: ' + vehicleTrip.num_passengers + '人/' + vehicleTrip.max_seat_capacity +
                        '座' +
                        '&nbsp;&nbsp;&nbsp;&nbsp;' + vehicleTrip.adcRoutePrice.price + '元/位' }}</div>
                    <div class="text item">
                        {{ vehicleTrip.name }}
                        {{ vehicleTrip.phone + '&nbsp;&nbsp;&nbsp;&nbsp;' }}
                        <el-button class="call" type="primary" :icon="Phone">呼叫司机</el-button>
                    </div>
                </el-card>
                <div class="map">
                    <Map>

                    </Map>
                </div>


                <el-row class="num">
                    <el-button v-for="item in numingroup" :key="item.value" :value="item.value" @click="selectnum(item.value)">
                        {{ item.num }}
                    </el-button>
                </el-row>

                <el-row class="select">
                    <el-button type="primary" size="large" color="#337ecc" @click="back()">
                        取消加入
                    </el-button>
                    <el-button type="primary" size="large" color="#337ecc" @click="carpooling()">
                        我要拼车
                    </el-button>
                </el-row>
            </el-main>
        </el-container>
    </div>
</template>

<script setup>
    import { Back, Phone } from '@element-plus/icons-vue'
    import { ref, onMounted, watchEffect, watch, reactive } from 'vue'
    import { ElLoading } from 'element-plus'
    import { ElMessage } from 'element-plus'
    import Map from '../components/Map.vue'
    import service from "../utils/request.js";
    import { useUsersStore } from "../stores/user";
    import { useRouter } from "vue-router";
    import { useRoute } from "vue-router";
    const router = useRouter()
    const route = useRoute()
    const store = useUsersStore()
    const vehicleTripId = ref(route.query.id)
    const id = ref(localStorage.getItem('userId'))
    const sendId = ref('')
    const formattedDate=ref('')
    const formattedTime=ref('')
    function connectWebSocket() {
        let userId = localStorage.getItem('userId');
        const wsUrl = `${import.meta.env.VITE_BASE_WS}/websocket-passengertrip/${userId}`;
        if ("WebSocket" in window) {
            let ws = new WebSocket(wsUrl);
            store.setWebsocket(ws);
        } else {
            alert("不支持websocket");
        }

        store.websocket.onerror = function () {
            console.log("WebSocket连接发生错误");
        };

        store.websocket.onopen = function () {
            console.log("WebSocket连接成功");
        };

        store.websocket.onmessage = function (event) {
            console.log(event.data);
            store.setMessage(event.data);  // 设置消息内容到store
        };
    }
    //此处为websocket监听方法，已完成监听
    // 定义一个 reactive 对象来保存 form 数据
    const form = reactive({
        message: '',
        passengerId:'',
        tripId:'',
        passengers: ''
    });
    //使用 watchEffect 来观察 store.message，并在其变化时更新 form 对象
    watchEffect(() => {
        if (store.message) {
            // message 是一个 JSON 字符串，解析为 JavaScript 对象
            const data = JSON.parse(store.message);
            for (const key in data) {
                if (data.hasOwnProperty(key)) {
                    form[key] = data[key];
                }
            }
        }
    });

    //人数选择按钮组
    const numingroup = ref([
        {
            value: 1,
            num: '1人'
        },
        {
            value: 2,
            num: '2人'
        },
        {
            value: 3,
            num: '3人'
        },
        {
            value: 4,
            num: '4人'
        }
    ])
    const passenger = ref({
        id: '',
        name: '',
        username: '',
        password: '',
        email: '',
        phone: ''
    })
    //车辆行程与价格表联查获得的数据
    const vehicleTrip = ref({
        id: '',
        vehicle_id: '',
        name: '',
        username: '',
        phone: '',
        vehicle_license: '',
        start_time: '',
        start_date: '',
        max_seat_capacity: '',
        status: '',
        vehicle_route_id: '',
        start_location_latitude: '',
        start_location_longitude: '',
        start_location_name: '',
        is_deleted: '',
        num_passenger: '',
        adcRoutePrice: {
            id: '',
            route: '',
            price: '',
            is_deleted: '',
            start_route: '',
            end_route: ''
        },
    })
    //我发送的消息体
    const CarpoolRequest = ref({
        tripId: '',
        passengerId:'',
        name: '',
        contact: '',//电话
        startLocation: '',//起始地
        endLocation: '',//目的地
        passengers: '',
        startLocationName: '',
        startLocationLongitude: '',//起始地点经度
        startLocationLatitude: ''//起始地点纬度
    })
    //我需要拼接后上传的数据
    const passengerTrip = ref({
        id: '',
        passengerId: '',
        name: '',
        username: '',
        phone: '',
        passengerRouteId: '',
        route: '',
        price: '',
        startTime: '',
        startDate: '',
        passengerTripNumPassengers: '',
        status: '',
        startLocationName: '',
        startLocationLongitude: '',
        startLocationLatitude: '',
        vehicleTripId: '',
        isDeleted: ''
    })
    const selectnum= (value) =>{
        passengerTrip.value.passengerTripNumPassengers=value
        console.log(passengerTrip.value.passengerTripNumPassengers)
    }
    onMounted(() => {
        connectWebSocket();
        Promise.all([loading(), getvehicleTripAndPrice(), getpassenger()])
        console.log(vehicleTrip.value)
    })
    const getvehicleTripAndPrice = () => {
        service.get(`passenger-trip/VehicleTripAndPrice/${vehicleTripId.value}`)
            .then(res => {
                if (res.data.status == '等待乘客') {
                    vehicleTrip.value = res.data
                    console.log(vehicleTrip.value)
                    // 从MySQL输出的日期和时间时间戳
                    var dateFromMySQL = vehicleTrip.value.start_date; // 日期时间戳
                    var timeFromMySQL = vehicleTrip.value.start_time; // 时间时间戳
                    console.log(vehicleTrip.value.start_date)
                    console.log(vehicleTrip.value.start_time)
                    // 使用Date对象将时间戳转化为JavaScript日期对象
                    var date = new Date(dateFromMySQL);
                    var time = new Date(timeFromMySQL);

                    // 将JavaScript日期对象转化为所需的时间字符串格式
                    formattedDate.value = date.toLocaleDateString(); // 将日期部分格式化为日期字符串
                    formattedTime.value = time.toLocaleTimeString(); // 将时间部分格式化为时间字符串

                    // 输出结果
                    console.log("日期：" + formattedDate);
                    console.log("时间：" + formattedTime);
                } else {
                    statusErro();
                    back()
                }
            })
    }

    const carpooling = () => {
        getvehicleTripAndPrice()
        const numPassengers = parseInt(passengerTrip.value.passengerTripNumPassengers, 10);
        const numPassenger = parseInt(vehicleTrip.value.num_passengers, 10);
        const maxSeatCapacity = parseInt(vehicleTrip.value.max_seat_capacity, 10);
        console.log(numPassengers)
        console.log(numPassenger)
        console.log(maxSeatCapacity)
        if (passengerTrip.value.passengerTripNumPassengers == '') {
            selectErro()
        } else if(numPassengers + numPassenger > maxSeatCapacity){
            fullErro()
        }
        else {

            sendwebSocket()//向司机端发送消息
            loadingJeDan()

        }
    }
    const sendwebSocket = () => {
        CarpoolRequest.value.tripId = vehicleTrip.value.id
        CarpoolRequest.value.passengerId = passenger.value.id
        CarpoolRequest.value.passengers=passengerTrip.value.passengerTripNumPassengers
        CarpoolRequest.value.name = passenger.value.username
        CarpoolRequest.value.contact = passenger.value.phone
        CarpoolRequest.value.startLocation = vehicleTrip.value.adcRoutePrice.start_route
        CarpoolRequest.value.endLocation = vehicleTrip.value.adcRoutePrice.end_route
        CarpoolRequest.value.startLocationName = store.address
        CarpoolRequest.value.startLocationLongitude = store.startLocationLongitude
        CarpoolRequest.value.startLocationLatitude = store.startLocationLatitude
        console.log(CarpoolRequest.value)
        service.post(`passenger-trip/pooling`, CarpoolRequest.value)
            .then(response => {
                console.log('成功', response);
            })
            .catch(error => {
                console.log('失败', error);
            });
    }


    const insterPassengerTrip = () => {
        passengerTrip.value.passengerId = passenger.value.id
        passengerTrip.value.name = passenger.value.name
        passengerTrip.value.username = passenger.value.username
        passengerTrip.value.phone = passenger.value.phone
        passengerTrip.value.passengerRouteId = vehicleTrip.value.vehicle_route_id
        passengerTrip.value.route = vehicleTrip.value.adcRoutePrice.route
        passengerTrip.value.price = vehicleTrip.value.adcRoutePrice.price
        // 创建一个新的Date对象，它将包含当前日期和时间
        var currentDate = new Date();
        // 获取当前时间的小时、分钟和秒
        var hours = currentDate.getHours();
        var minutes = currentDate.getMinutes();
        var seconds = currentDate.getSeconds();
        // 如果需要，可以将时间格式化成字符串，以便与MySQL的TIME类型匹配
        var formattedTime = hours + ':' + minutes + ':' + seconds;
        passengerTrip.value.startTime = formattedTime
        // 创建一个新的Date对象，它将包含当前日期
        var currentDate = new Date();
        // 获取年、月和日
        var year = currentDate.getFullYear();
        var month = currentDate.getMonth() + 1; // 月份从0开始，所以需要加1
        var day = currentDate.getDate();
        // 如果需要，可以将日期格式化成字符串，以便与MySQL的DATE类型匹配
        var formattedDate = year + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
        passengerTrip.value.startDate = formattedDate
        passengerTrip.value.status = '已接受'
        passengerTrip.value.startLocationName = vehicleTrip.value.start_location_name
        passengerTrip.value.startLocationLongitude = store.startLocationLongitude
        passengerTrip.value.startLocationLatitude = store.startLocationLatitude
        passengerTrip.value.vehicleTripId = vehicleTrip.value.id
        passengerTrip.value.isDeleted = 0
        console.log(passengerTrip.value)
        service.post('passenger-trip/passengerTrip/inster', passengerTrip.value)
            .then(res => {
                sendId.value = res.data
                console.log(sendId.value)
                router.push({
                    path: '/pcsuccess',
                    query: { childrenImf: sendId.value }

                })
            })
    }

    const getpassenger = () => {
        service.get(`passenger-trip/passenger/query/${id.value}`)
            .then(res => {
                passenger.value = res.data
            })
    }

    const back = () => {
        router.push('/search');
    }

    //加载，获得address，经度维度
    const loading = () => {

        const loading = ElLoading.service({
            lock: true,
            text: '请稍等，正在定位中',
            background: 'rgba(0, 0, 0, 0.7)',
        })
        setTimeout(() => {
            loading.close()
        }, 3000)
    }

    //接单加载
    const loadingJeDan = () => {

        const loadingJeDan = ElLoading.service({
            lock: true,
            text: '司机接单中',
            background: 'rgba(0, 0, 0, 0.7)',
        })
        watch(() => form.message, (newValue) => {
            if (newValue == '同意接单') {
                Jiedan()
                console.log(newValue)
                loadingJeDan.close()
                store.message=''
                insterPassengerTrip()
            } else {
                driverSayNo()
                store.message=''
                back()
            }
        });
        setTimeout(() => {
            if (form.message == '') {
                loadingJeDan.close()
                timeErro()
                back()
            }
        }, 40000)
    }

    //提示区
    const statusErro = () => {
        ElMessage('手慢了哦，该拼车已取消或完成')
    }
    const selectErro = () => {
        ElMessage('请选择乘车人数')
    }
    const fullErro = () => {
        ElMessage('人数超过剩余座数，请选择合适的人数')
    }
    const timeErro = () => {
        ElMessage('司机长时间未回复，已为您返回')
    }
    const driverSayNo = () => {
        ElMessage('司机已拒绝，已取消，请重新选择')
    }
    const Jiedan = () => {
        ElMessage('司机已接单')
    }
</script>
<style>
    .el-container {
        display: flex;
        flex-direction: column;
        height: 100%;
    }

    .el-header {
        background-color: #a0cfff;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
    }

    .el-main {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        margin: 0;
        padding: 0;
    }

    .text {
        font-size: 14px;
    }

    .item {
        padding: 4% 0;
    }

    .box-card {
        margin: 0;
        padding: 0;
        width: 100%;
        display: flex;
        flex-direction: column;
        justify-content: space-evenly;
    }

    .call {
        color: #a0cfff;
    }

    .map {
        margin-top: 5%;
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-around;
    }



    .num {
        margin-top: 5%;
        padding: 5%;
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-around;
    }

    .select {
        padding: 5%;
        padding-bottom: 10%;
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-around;
    }
</style>